import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/components/Layout'
import Login from '@/views/Login'

Vue.use(Router)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard'),
        meta: { title: '仪表盘' }
      },
      {
        path: 'store',
        name: 'Store',
        component: () => import('@/views/store/StoreManagement'),
        meta: { title: '门店管理' }
      },
      {
        path: 'banner',
        name: 'Banner',
        component: () => import('@/views/banner/BannerManagement'),
        meta: { title: '轮播图管理' }
      },
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/user/UserManagement'),
        meta: { title: '用户管理' }
      }
    ]
  }
]

const router = new Router({
  mode: 'history',
  routes
})

// 修改导航守卫逻辑
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  
  // 如果用户未认证且访问的不是登录页，重定向到登录页
  if (!isAuthenticated && to.path !== '/login') {
    return next('/login')
  }
  
  // 如果用户已认证但访问的是登录页，重定向到首页
  if (isAuthenticated && to.path === '/login') {
    return next('/dashboard')
  }
  
  // 其他情况正常放行
  next()
})

export default router